import sys
from urlparse import urlunparse

from sqlalchemy import create_engine
from dbmigrate.datasource import BaseDataSource


class DataSource(BaseDataSource):
    
    scheme = "mysql"
    
    show_tables_sql = "SHOW databases LIKE '%(db)s'"
    select_applied_revisions_sql =  "SELECT %(schema_revision_col)s FROM %(db)s.%(schema_table)s"
    insert_revision_sql =  "INSERT INTO %(db)s.%(schema_table)s (%(migration_package_col)s, %(schema_revision_col)s) VALUES (%(package)s, %(revision)s)"
    delete_revision_sql = "DELETE FROM %(db)s.%(schema_table)s WHERE %(schema_revision_col)s = %(revision)s"
    initial_migration = [
    (
"""CREATE DATABASE %(db)s""",
"""DROP DATABASE %(db)s"""
    ), (
"""CREATE TABLE %(db)s.%(schema_table)s (
            %(id_col)s INTEGER PRIMARY KEY AUTO_INCREMENT,
            %(migration_package_col)s VARCHAR(128) NOT NULL,
            %(schema_revision_col)s BIGINT UNSIGNED NOT NULL
    )
""", 
"""DROP TABLE %(db)s.%(schema_table)s"""
    ),
]
    
    def __init__(self):
        super(DataSource, self).__init__()
        self._engine = None

    def dbi_placeholder(self):
        return '%s'
    
    def read_options(self, options, args):
        self.assert_has_required(options, args)
        for (i, x) in enumerate(['admin_user', 'admin_pw', 'user', 'pw', 'db']):
            self.expansionFromArg(args, x, i, None)
        self.expansionFromArg(args, 'host', 5, 'localhost')
        self.expansionFromArg(args, 'port', 6, 3306)

    def assert_has_required(self, options, args):
        if len(args) < 5:
            options.error("Expected the arguments: ADMIN_USER ADMIN_PW USER PW DB [HOST [PORT]]") 

    def read_command(self, cmd):
        for x in ['admin_user', 'admin_pw', 'user', 'pw', 'db']:
            self.expansionFromCommand(cmd, x)
        self.expansionFromCommand(cmd, 'host', 'localhost')
        self.expansionFromCommand(cmd, 'port', 3306)
            
    def read_config_file(self, config):
        for x in ['admin_user', 'admin_pw', 'user', 'pw', 'db']:
            self.expansionFromIniOption(config, x)
        self.expansionFromIniOption(config, 'host', 'localhost')
        self.expansionFromIniOption(config, 'port', 3306)
    
    def admin_uri(self):
        # Connect to the master database by default
        netloc = '%(admin_user)s:%(admin_pw)s@%(host)s:%(port)s' % self.expansions
        return urlunparse([self.scheme, netloc, 'mysql', None, None, None])

    migration_uri = admin_uri

    def app_uri(self):
        # Connect to the master database by default
        netloc = '%(user)s:%(pw)s@%(host)s:%(port)s' % self.expansions
        return urlunparse([self.scheme, netloc, self.expansions['db'], None, None, None])

    def set_up_unit_test(self):
        for x in ['user', 'pw', 'db']:
            self.expansionFromRandomString(x, 8, '_tmp')

    def print_unit_test_information(self):
        msg = "MySQL database, username, and password are '%s', '%s', and '%s'"
        subst = tuple(self.expansions[x] for x in ['db', 'user', 'pw'])
        print >> sys.stderr, msg % subst

    def tear_down_unit_test(self):
        pass
    